package com.txm.qqserver.service;

import com.txm.qqcommon.File_;
import com.txm.qqcommon.Message;
import com.txm.qqcommon.MessageType;
import com.txm.qqcommon.Response;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;

public class SendFile extends Thread{

    Response res;

    File sendFile;

    public SendFile(Response res, File sendFile) {
        this.res = res;
        this.sendFile = sendFile;
    }

    @Override
    public void run() {
        Message msg = (Message) res.getObject();
        byte[] bytes = new byte[1024];
        int readInt = 0;
        Message message = new Message();
        message.setSendTime(msg.getSendTime());
        while (true) {
            try {
                Thread.sleep(1000);
                ServerConnectServerThread thread = (ServerConnectServerThread) ManageClientThreads.getMcts().get(msg.getGetter());
                if (thread == null) {
                    System.out.println(msg.getGetter() + "用户不在线。");
                    continue;
                }
                System.out.println(msg.getGetter() + "在线开始发送文件");
                FileInputStream fis = new FileInputStream(sendFile);
                message.setSender(msg.getSender());
                message.setGetter(msg.getGetter());
                message.setMsgType(MessageType.MESSAGE_RECEIVE_FILE);
                File_ file1 = new File_(sendFile);

                while ((readInt = fis.read(bytes)) != -1) {
                    ObjectOutputStream oos = new ObjectOutputStream(thread.accept.getOutputStream());
                    file1.setDataCut(bytes);
                    file1.setDataCut_size(readInt);
                    message.setObject(file1);
//                System.out.println(message);
                    oos.writeObject(message);
                    System.out.println(file1.getProgress());
                }
                fis.close();
                break;
            } catch (Exception e) {
                System.out.println(this.getName() + ":" + e);
            }
        }
        System.out.println("文件已发送给" + msg.getGetter());
    }
}
